package utils.cli;

import com.alibaba.fastjson.JSON;
import entity.ConfigFile;
import entity.YouGetVideo;
import lombok.extern.slf4j.Slf4j;
import utils.json.InitConfig;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * 执行you-get命令，实现获取真实下载地址，下载到本地等功能。
 */
@Slf4j
public class CLIUtil {
    private static final ConfigFile config = InitConfig.getInstance().getConfig();

    /**
     * 根据B站视频链接获取真实下载地址。
     *
     * @param videoLink B站视频链接
     * @return 包含下载地址集合的对象
     */
    public static YouGetVideo getVideoRealLink(String videoLink) {
        log.info("You-Get：链接：" + videoLink + " 状态：获取真实下载链接。");
        String json = exeCmd("you-get --json " + videoLink);
        return JSON.parseObject(json, YouGetVideo.class);
    }

    /**
     * 调用CLI执行下载视频的命令
     *
     * @param videoLink B站视频链接
     */
    public static void downloadVideo(String videoLink) {
        String downloadPath = config.getYouGet().getDir();
        String command = "you-get -o " + downloadPath + " " + videoLink;
        log.info("You-Get： 链接：" + videoLink + " 状态：开始下载");
        exeCmd(command);
    }

    /**
     * 执行命令
     *
     * @param commandStr 命令字符串
     * @return 返回格式化后的执行结果字符串
     */
    private static String exeCmd(String commandStr) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        try {
            Process p = Runtime.getRuntime().exec(commandStr);
            p.getInputStream();
            br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
                //打印实时执行结果
//                log.info(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        log.info("CLI：" + commandStr + " 执行完毕。");
        return sb.toString();
    }
}
